<template>
    <el-dialog v-model="drawer" title="核销" width="600px" :append-to-body="true" @close="close" destroy-on-close>
        <el-tabs v-model="type" class="demo-tabs">
            <el-tab-pane label="卡卷核销" name="first">
                <el-form ref="ruleRefForm" :model="form" :rules="rules" size="small" label-width="180px">
                    <!-- <el-form-item label="核销类型" prop="type">
                        <el-select v-model="form.type" placeholder="请选择" size="small" style="width:220px">
                            <el-option
                                v-for="item in typeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="核销用户" prop="memberId">
                        <el-select v-model="form.memberId" filterable clearable placeholder="选择核销用户" style="width: 220px"
                            @change="selectUser">
                            <el-option v-for="item in userList" :key="item.id" :label="item.nickname + ' - ' + item.mobile"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="核销卡" prop="myCardId">
                        <el-select v-model="form.myCardId" clearable placeholder="选择卡卷核销" style="width: 220px"
                            @change="selectCard">
                            <el-option v-for="item in cardList" :key="item.id" :label="item.cardName" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="核销码" prop="code">
                        <el-input placeholder="请输入" v-model="form.code" style="width:220px"></el-input>
                    </el-form-item> -->
                    <el-table :data="skuList" height="250" style="width: 100%" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" />
                        <el-table-column label="商品图" prop="skuDefaultImg">
                            <template #default="scope">
                                <el-image style="width: 30px; height: 30px" :src="scope.row.skuDefaultImg" fit="cover"
                                    :preview-src-list="[scope.row.skuDefaultImg]" :preview-teleported="true">
                                    <template #error>
                                        <div class="image-slot">
                                            <el-icon><ele-Picture /></el-icon>
                                        </div>
                                    </template>
                                </el-image>
                            </template>
                        </el-table-column>
                        <el-table-column prop="skuName" label="商品名称" />
                    </el-table>

                </el-form>
            </el-tab-pane>
            <el-tab-pane label="订单核销" name="second">
                <el-form ref="ruleRefForm" :model="form" :rules="rules" size="small" >
                    <el-form-item label="核销单号" label-width="180px">
                        <el-input v-model="orderSn" placeholder="请输入订单号" style="width: 220px;" maxlength="13" @input="handleInput"></el-input>
                        <el-button type="primary" round style="margin-left: 20px" @click="searchInfo">搜 索</el-button>
                    </el-form-item>
                    <el-form-item v-if="orderInfo">
                        <div style="margin-left: 20px; margin-bottom: 20px;">订单支付金额：{{ orderInfo.payAmount }}</div>
                        <div style="margin-left: 20px; margin-bottom: 20px;">购买者：{{ orderInfo.customerName }}</div>
                        <el-table :data="orderInfo.orderItemList" height="250" style="width: 100%" >
                            <el-table-column label="商品图" prop="spuPic">
                                <template #default="scope">
                                    <el-image style="width: 30px; height: 30px" :src="scope.row.spuPic" fit="cover"
                                        :preview-src-list="[scope.row.spuPic]" :preview-teleported="true">
                                        <template #error>
                                            <div class="image-slot">
                                                <el-icon><ele-Picture /></el-icon>
                                            </div>
                                        </template>
                                    </el-image>
                                </template>
                            </el-table-column>
                            <el-table-column prop="skuName" label="商品名称" />
                            <el-table-column prop="skuPrice" label="商品价格" />
                            <el-table-column prop="skuQuantity" label="商品数量" />
                        </el-table>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>




        <template #footer>
            <el-row justify="center">
                <el-button type="primary" size="small" @click="submit(ruleRefForm)">提交</el-button>
                <el-button type="default" size="small" @click="cancel(ruleRefForm)">取消</el-button>
            </el-row>
        </template>
    </el-dialog>
</template>

<script>
import { computed, reactive, toRefs, ref, onMounted } from 'vue'
import { useOrderApi } from '/@/api/order/index'
import { ElMessage } from 'element-plus'
import api from '/@/api/commonApi'

export default {
    name: 'Verification',
    props: {
        dialogDrawer: {
            type: Boolean,
            default: false
        },
        userList: {
            type: Array,
            default() {
                return []
            }
        }
    },
    emits: ['onSubmit', 'update:dialogDrawer'],
    setup(props, context) {
        const { dialogDrawer, userList } = toRefs(props)
        const drawer = computed({
            get: () => dialogDrawer.value,
            set: val => {
                reset()
                context.emit('update:dialogDrawer', val)
            }
        })
        const ruleRefForm = ref()
        const orderApi = useOrderApi()
        const state = reactive({
            type: 'first',
            orderSn: '',
            orderInfo: {},
            form: {
                type: '1',
                memberId: '',
                myCardId: '',
                code: '',
                skuList: []
            },
            cardList: [],
            skuList: [],
            rules: {
                // type: [{ required: true, trigger: 'blur', message: '请选择类型' }],
                memberId: [{ required: true, trigger: 'blur', message: '请选择会员' }],
                myCardId: [{ required: true, trigger: 'blur', message: '请选择卡卷' }],
                code: [{ required: true, trigger: 'blur', message: '请输入核销码' }]
            },
            typeList: [{
                label: '次卡',
                value: 1
            }, {
                label: '会员卡',
                value: 2
            }]
        })
        const close = () => {
            context.emit('update:dialogDrawer', false)
        }
        const submit = formEl => {
            if (!formEl) return
            formEl.validate((valid) => {
                if (valid) {
                    if (state.type == 'first') {
                        orderApi.verifyOrder(state.form).then(() => {
                            ElMessage.success('核销成功')
                            context.emit('onSubmit', true) // 提交
                            context.emit('update:dialogDrawer', false)
                        })
                    } else {
                        if(state.orderSn){
                            api.orderFinish({orderSn: state.orderSn}).then(res => {
                                ElMessage.success('核销成功')
                                context.emit('onSubmit', true) // 提交
                                context.emit('update:dialogDrawer', false)
                            })
                        }else {
                            ElMessage.warning("请填写订单号")
                        }
                    }
                }
            })
        }
        const cancel = formEl => {
            if (!formEl) return
            formEl.resetFields()
            context.emit('update:dialogDrawer', false)
        }
        const reset = () => {
            state.form = {
                type: '',
                memberId: '',
                myCardId: '',
                code: '',
                skuList: []
            }
            state.skuList = []
            state.orderInfo = {}
            state.orderSn = ''

        }
        // 获取用户卡卷
        const selectUser = (val) => {
            if (state.form.memberId != '' && state.form.memberId != null) {
                state.form.myCardId = ''
                state.skuList = []
                state.form.skuList = []
                api.getMyCards({
                    memberId: state.form.memberId
                }).then(res => {
                    state.cardList = res.data
                })
            } else {
                state.cardList = []
                state.skuList = []
                state.form.skuList = []
                state.form.myCardId = ''
            }

        }
        // 选择卡项
        const selectCard = val => {
            if (val) {
                state.form.skuList = []
                let list = []
                state.cardList.forEach(item => {
                    if (item.id == val) {
                        list = item.skuInfoList
                        return
                    }
                });
                state.skuList = list
            } else {
                state.skuList = []
                state.form.skuList = []
            }
        }
        const handleSelectionChange = (val) => {
            console.log(val);
            state.form.skuList = val
            state.form.skuList.forEach(val => {
                val.useCard = 1
            })
        }
        const handleInput = (value) => {
            const reg = /^[\d\.]+$/;
      
            if (value && !reg.test(value)) {
                state.orderSn = value.replace(/[^\d\.]/g, '');
            }
        }
        const searchInfo = () => {
            if(state.orderSn.length > 0) {
                if (state.orderSn.length == 13) {
                    api.orderInfoBySn({orderSn: state.orderSn}).then(res => {
                        state.orderInfo = res.data
                    })
                }else{
                    state.orderInfo = {}
                    ElMessage.warning('请输入正确的订单号')
                }
            }
        }

        onMounted(() => {

        })
        return {
            ...toRefs(state),
            drawer,
            close,
            ruleRefForm,
            submit,
            cancel,
            selectUser,
            reset,
            selectCard,
            handleInput,
            searchInfo,
            handleSelectionChange,
        }
    }
}
</script>

<style></style>